import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';

let Tim = {
  options: {
    SDKAppID: 1600053911 // 接入时需要将0替换为您的云通信应用的 SDKAppID，类型为 Number
  },
  dom: null,
  userID: 0,
  // userID: 40,
  userSig: '',
}

// 创建实例
Tim.CreateTim = async (data) => {
  Tim.userID = uni.getStorageSync('user') ? JSON.parse(uni.getStorageSync('user')).info.id : ''
  setTimeout(async() => {
    Tim.userSig = data
    Tim.dom = await TencentCloudChat.create(Tim.options)
    console.log(Tim.dom)
    Tim.dom.setLogLevel(4)
    Tim.dom.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin })
    Tim.Login() // 创建完实例进行登陆
    if(!Tim.dom) {
      setTimeout(() => {
        Tim.CreateTim(data)
      }, 1000)
    }
  }, 200)
}
// 登陆
Tim.Login = async () => {
  Tim.dom.login({ userID: Tim.userID.toString(), userSig: Tim.userSig}).then(res => {
    // console.log(res, '登陆')
    Tim.dom.on(TencentCloudChat.EVENT.SDK_READY, (res) => {
        if(res.name === 'sdkStateReady') {
          Tim.updateUserInfo()
        }
    })
  }).catch(err => {
    console.log('登陆失败', err)
  })
}
// 登出
Tim.LoginOut = () => {
  Tim.dom.logout().then(res => {
    console.log('登出成功')
  }).catch(err => {
    console.log('登出失败', err)
  })
}
// 销毁
Tim.destroy = () => {
  Tim.dom.destroy()
}

Tim.updateUserInfo = () => {
  let info = JSON.parse(uni.getStorageSync('user'))
  console.log('------更新用户', info)
  Tim.dom.updateMyProfile({
    nick: info.info.name,
    avatar: info.info.avatar,
  }).then(res => {
    console.log('====', res)
  })
}


//  发送消息
Tim.sendMessage = async (toId, content) => {
  console.log('Tim',Tim);
  let message = await Tim.dom.createTextMessage({
    to: toId,
    conversationType: TencentCloudChat.TYPES.CONV_C2C,
    payload: {
      text: content
    }
  })
  try {
    const result = await Tim.dom.sendMessage(message)
    return result;
  }catch (err) {
    await Tim.reSendMessage(message)
    throw err;
  }
}
// 重新发送
Tim.reSendMessage = async (message) => {
  try {
    const result = await Tim.dom.resendMessage(message)
  }catch (err) {
    console.log(err)
  }
}

// 获取消息列表
Tim.getMessageList = async (chatId, nextReqMessageID) => {
  const result = await Tim.dom.getMessageList({
    conversationID: 'C2C' + chatId, //对方id
    nextReqMessageID: nextReqMessageID // 默认为 ''第一次， 第二次的时候就是返回的result
  })
  Tim.noReadCount()
  return result
}
//获取消息列表
Tim.getAllConversationList = async () => {
  // 获取全量的会话列表
  let promise = Tim.dom.getConversationList();
  let list = promise.then(function(imResponse) {
    const conversationList = imResponse.data.conversationList; // 全量的会话列表，用该列表覆盖原有的会话列表
    return conversationList
  }).catch(function(imError) {
    console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
  });
  return list
}

// 获取消息未读
Tim.noReadCount = async () => {
  const result = await Tim.dom.setMessageRead({conversationID: 'C2C' + Tim.userID})
  return result
}

// 监听消息
Tim.getMessageNotice = () => {
  let msg = Tim.dom.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, async (message) => {
    return message[0]
  })
  return msg
}

// 监听会话列表
Tim.getConversationListNotice = () => {
  Tim.dom.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, async (conversationList) => {
    Tim.dom.on(TencentCloudChat.EVENT.SDK_READY, (res) => {
      console.log('监听会话列表--------', res)
    })
  })
}

/* 是否置顶消息
* isPinned true: 置顶 false：取消置顶*/

Tim.setTop = async (ID, isPinned) => {
  try {
    const result = await Tim.dom.pinConversation({
      isPinned: isPinned,
      conversationID: 'C2C' + Tim.userID,
    })
  }catch (e) {
    console.log(e)
  }
}

// 删除会话，并且会清空聊天记录
Tim.deleteConversation = async (ID) => {
  try {
    const result = await Tim.dom.deleteConversation({
      conversationID: 'C2C' + Tim.userID
    })
  }catch (e) {
    console.log(e)
  }
}
export default Tim
